package utils

import (
	"context"
	"ginblog/utils/errmsg"
	"github.com/qiniu/api.v7/v7/auth/qbox"
	"github.com/qiniu/api.v7/v7/storage"
	"os"
)

//七牛文件上传
func UploadFile(localFile string, uploadKey string) (string, int) {
	key := uploadKey
	//key := ""//自定义保存到七牛的文件名

	//上传的凭证
	putPolicy := storage.PutPolicy{
		Scope: Bucket,
	}

	mac := qbox.NewMac(AccessKey, SecretKey)
	upToken := putPolicy.UploadToken(mac)

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}

	putExtra  := storage.PutExtra{
	//	Params: map[string]string{
	//		"x:name": "github logo",
	//	},
	}

	err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, &putExtra)
	if err != nil {
		return err.Error(), errmsg.ERROR
	}

	//文件上传成功，删除服务器图片
	os.Remove(localFile);
	return QiniuServer + ret.Key, errmsg.SUCCESS
}